<template>
  <div class="birthday-edit-container">
    <van-datetime-picker
      v-model="currentDate"
      type="date"
      title="选择生日日期"
      :min-date="minDate"
      :max-date="maxDate"
      :formatter="formatter"
      @cancel="$emit('close')"
      @confirm="onConfirm"
    />
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { updateUserProfileAPI } from '../../../api/index.js'

export default {
  name: 'BirthdayEdit',
  props: {
    userBirthday: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      minDate: new Date(1980, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(this.userBirthday)
    }
  },
  methods: {
    formatter (type, val) {
      if (type === 'year') {
        return `${val}年`
      } else if (type === 'month') {
        return `${val}月`
      }
      return val
    },
    async onConfirm () {
      try {
        const { data: res } = await updateUserProfileAPI({
          birthday: dayjs(this.currentDate).format('YYYY-MM-DD')
        })
        console.log(res)
        // console.log(dayjs(this.currentDate).format('YYYY-MM-DD'))
        // 更新视图
        this.$emit('update:userBirthday', dayjs(this.currentDate).format('YYYY-MM-DD'))

        // 关闭弹框
        this.$emit('close')
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style scoped>

</style>
